package Power_Asisst.main;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.AdapterView.OnItemClickListener;
public class Power_AsisstActivity extends Activity {
	
	UDP_Services SVBroadCast= new UDP_Services();
	Untils SVUntils = new Untils();
	private TextView serverStatus;
	private ListView listViewItem;
	static final int PROGRESS_DIALOG=0;
	int currentNumber;
	final Handler handler = new Handler();
	public static String SERVERIP="";
	private ServerSocket serverSocket;
	public static int SERVERPORT=8080;
	public  String result="None";
	public int StatusConnect=0;
	private List<String> arr_DSKetNoi = null;
	private ArrayAdapter<mItems> listadapter = null;
	
	private List<String> listConnection = null;
	 
	//private  String[]a ;
	AlertDialog.Builder builder;
	AlertDialog alertDialog;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       final TextView myTextView =(TextView)findViewById(R.id.textViewReceive);
       final Button btnSend =(Button) findViewById(R.id.btnSend);
       final Button btnExit = (Button) findViewById(R.id.btnExit);
       final Button btnConnect=(Button)findViewById(R.id.btnConnect);
      
       listViewItem = (ListView)findViewById(R.id.lv_DanhsachKetNoi);
       serverStatus=(TextView)findViewById(R.id.textViewReceive);
       builder = new AlertDialog.Builder(this);
       builder.setTitle("Các client hiện có!!!");
       
       arr_DSKetNoi = new ArrayList<String>();
       listConnection = new ArrayList<String>();
      
       SERVERIP=SVUntils.getLocalIPAddress();
   		if(StatusConnect!=1)
   		{
   			
   			Thread testListenTCP = new Thread(new ServerThread());
			testListenTCP.start();
   		}
   		else{
   			updateStatus(listConnection);
   		}
			
       		listViewItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					
			/*		CheckBox cb1 = (CheckBox)arg1;
					mItems planet1 = (mItems)cb1.getTag();*/
					//mItems planet1.setChecked(((CheckBox)arg1).isChecked());
					// TODO Auto-generated method stub
					mItems planet = listadapter.getItem(arg2);
					planet.toggleChecked();
					SelectViewHolder viewHolder = (SelectViewHolder) arg1
							.getTag();
					CheckBox cb = viewHolder.getCheckBox();
					cb.setChecked(planet.isChecked());
					boolean a = planet.isChecked();
					
					//viewHolder.getCheckBox().setChecked(planet.isChecked());
				
					Object o = listViewItem.getItemAtPosition(arg2);
					String Chuoi  = o.toString();
					if(a==true)
					{
						listConnection.add(Chuoi);
					}
				
					Toast.makeText(getApplicationContext(), Chuoi +":" +a, Toast.LENGTH_SHORT).show();
					//updateStatus();
				}
			});
			
        btnSend.setOnClickListener(new View.OnClickListener() {
       
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
				try {
				//	show("");
					
					Thread testBroadCast = new Thread(new BroadCastThread());
					testBroadCast.start();
					
					
				} catch (Exception e) {
					// TODO: handle exception
					Log.d("Co loi trong chay Thread", e.toString());
				}
				
			}
		});
    btnExit.setOnClickListener(new View.OnClickListener() {
			
    	  
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				try {
				finish();
				android.os.Process.killProcess(android.os.Process.myPid());
				
					
				} catch (Exception e) {
					// TODO: handle exception
					Log.d("Loi khi exit", e.toString());
				}
			}
		});
       btnConnect.setOnClickListener(new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			updateStatus(listConnection);
			/*if(listConnection.size()>0)
			{
				final String arr_ClientConnect[] = new String[listConnection.size()];
        		
        		for(int i=0;i<listConnection.size();i++)
        		{
        			String a = listConnection.get(i);
        			arr_ClientConnect[i] = a;
        			
        		}
				builder.setSingleChoiceItems(arr_ClientConnect, -1, new DialogInterface.OnClickListener() {
				 public void onClick(DialogInterface dialog, int item) {
  		        Toast.makeText(getApplicationContext(), arr_ClientConnect[item], Toast.LENGTH_SHORT).show();
				 }
				});
				alertDialog = builder.create();
				alertDialog.show();
		}*/
		}
		});
       
    }
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(0, 1, Menu.NONE, "Products");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case 1:

			for (int i = 0; i < arr_DSKetNoi.size(); i++) {
				Log.d("pos : ", "" + arr_DSKetNoi.get(i));
			}
			break;
		}
		return super.onOptionsItemSelected(item);
	}
    public void updateStatus(List<String> client)
    {
    	//client = result;
    	if(StatusConnect==1)
    	{
    		testShow(client);
    	}
    }
    public void updateUI(String mess)
    {
    	try {
    		//arr_DSKetNoi.add(mess);
    		serverStatus.setText(mess);
    		ArrayList<mItems>ds = new ArrayList<mItems>();
        	if(arr_DSKetNoi.size()>0)
        	{
        		final String arr_Client[] = new String[arr_DSKetNoi.size()];
        		
        		for(int i=0;i<arr_DSKetNoi.size();i++)
        		{
        			String a = arr_DSKetNoi.get(i);
        			arr_Client[i] = a;
        			ds.add(new mItems(a));
        		}
        		//listViewItem.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,arr_DSKetNoi ));
        		listadapter = new ListViewCheckBox(this,ds);
        		listViewItem.setAdapter(listadapter);
        		 
      	        /*builder.setSingleChoiceItems(arr_Client, -1, new DialogInterface.OnClickListener() {
          		    public void onClick(DialogInterface dialog, int item) {
          		        Toast.makeText(getApplicationContext(), arr_Client[item], Toast.LENGTH_SHORT).show();
          		    }
          		});
          		alertDialog = builder.create();
          		alertDialog.show();*/
        		

        	}
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
    	
    }
    public void testShow(List<String> input)
	{
    	
    	// khue has change here 
    	//for(int i=0;i<input.size();i++)
    	{
    		
    		//final int sizeOfIP=Integer.valueOf(input.size());
    		//final String[] result=(String[]) input.toArray(new String[sizeOfIP]);
			final String[] result=input.get(0).split(",");
			new AlertDialog.Builder( this )
			.setTitle( "Thông Báo" )
			//.setMessage( "Bạn sẽ kết nối đến: "+result[0]+" ("+result[1]+")" )
			.setMessage( "Bạn sẽ kết nối đến cac client da chon" )
			.setPositiveButton( "Đồng ý", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					Log.d( "AlertDialog", "Positive" );
					try {
						
						/*Intent intent = new Intent();
				    	intent.setClass(getBaseContext(),RemotePowerPoint.class);
				    	intent.putExtra("IP", result[1]);
				    	intent.putExtra("Giao", "UDP");
						startActivity(intent);*/
						Intent intent = new Intent();
				    	intent.setClass(getBaseContext(),SdCard.class);
				    	// Khue modify to array list
				    	intent.putExtra("IP", result[1]);
				    	
				    	//intent.putExtra("sizeOfIP",sizeOfIP);
				    //	intent.putExtra("IP", result);
				    	
				    	intent.putExtra("Giao", "UDP");
				    	
						startActivity(intent);
						
					} catch (Exception e) {
						// TODO: handle exception
						Log.e("Loi intent moi", e.toString());
					}
					
				}
			})
			.setNegativeButton( "Hủy", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					Log.d( "AlertDialog", "Negative" );
				}
			} )
			.show();
    	}
	}
    public class ServerThread implements Runnable {
    	final Handler myHandler= new Handler();
	    public  void run() {
	    	
	        try {
	            if (SERVERIP != null) {
	            	(new Thread(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							final String status= SERVERIP;
							myHandler.post(new Runnable() {
								
								@Override
								public void run() {
									// TODO Auto-generated method stub
									updateUI(status);
								}
							});
						}
					})).start();
	                serverSocket = new ServerSocket(SERVERPORT);
	                while (true) {
	                    Socket client = serverSocket.accept();
	                    (new Thread(new Runnable() {
							
							@Override
							public void run() {
								// TODO Auto-generated method stub
								myHandler.post(new Runnable() {
									
									@Override
									public void run() {
										// TODO Auto-generated method stub
										updateUI("");
									}
								});
							}
						})).start();
	                   try {
	                        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
	                        final String line=in.readLine();
	                     
	                        while (line != null)
	                        {
	                        	handler.post(new Runnable() {
	                        		final String status=line;
		                            @Override
		                            public void run() {
		                            	int flag = 0;
	                            	for(int i=0;i<arr_DSKetNoi.size();i++ )
	                            	{
	                            		if(line.equals(arr_DSKetNoi.get(i)))
	                            		{
	                            			flag = 1;
	                            		}
	                            	}
	                            	if(flag==0)
	                            	{
	                            		arr_DSKetNoi.add(line);
	                            	}
		                           updateUI(line);
		                           result=line.toString();
		                           StatusConnect=1;
										
										
		                            }
		                        });
	                        	break;
	                        }
	                       
	                    
	                    } catch (Exception e) {
	                        handler.post(new Runnable() {
	                            @Override
	                            public void run() {
	                                serverStatus.setText("Xảy Ra Lỗi Hãy Thử Lại");
	                            }
	                        });
	                        Log.d("Co Loi", e.toString());
	                    }
	                }
	            } else {
	                handler.post(new Runnable() {
	                    @Override
	                    public void run() {
	                        serverStatus.setText("Không Thấy Wifi Được Mở");
	                    }
	                });
	            }
	        } catch (Exception e) {
	            handler.post(new Runnable() {
	                @Override
	                public void run() {
	                    serverStatus.setText("Không Thể Lấy Được IP Từ DHCP");
	                }
	            });
	            Log.d("Co Loi", e.toString());
	        }
	        serverStatus.setText(result);
	      
	    }
	    
	}
 


    public class BroadCastThread implements Runnable {
		public void run() {
			try {
				
				SVBroadCast.sendBroadCastInfoToAll();
			
			} catch (Exception e) {
				 Log.d("Co Loi", e.toString());
			}
			
		}
	}
    

}


